import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import { withRouter } from 'react-router';

import Select, { Option } from '@kuiper-components/select';
import Button from '@kuiper-components/button';

import DateRange from '../../../../../../components/DateRange';
import HostSearchInput from '../../../../../../components/HostSearchInput';
import s from './Toolbox.module.css';

const TRIGGER_OPTIONS = [
	{
		name: '周期性',
		value: 'schedule',
	},
	{
		name: '自定义',
		value: 'manual',
	},
];

function Toolbox({ className, reSearch, getDropdownRef, location }) {
	const filter = React.useMemo(
		() =>
			JSON.parse(new URLSearchParams(location.search).get('filter') || '{}'),
		[location]
	);
	const dateRange = React.useMemo(
		() => ({
			startTime: filter?.createTimeGTE,
			endTime: filter?.createTimeLTE,
		}),
		[location]
	);

	const handleDateChange = ({ startTime, endTime }) => {
		reSearch({
			createTimeGTE: startTime,
			createTimeLTE: endTime,
		});
	};
	const handleReset = () =>
		reSearch({
			taskTriggerType: undefined,
			createTimeGTE: undefined,
			createTimeLTE: undefined,
		});

	return (
		<div className={cn(className, s.toolbox)}>
			<HostSearchInput
				value={filter?.targetSearch}
				onChange={targetSearch => reSearch({ targetSearch })}
				className={s.item}
				placeholder="请输入风险地址"
			/>
			<div className={s.filters}>
				<Select
					placeholder="监测方式"
					className={s.item}
					value={filter?.taskTriggerType}
					onChange={taskTriggerType => reSearch({ taskTriggerType })}
					getPopupContainer={getDropdownRef}
				>
					{TRIGGER_OPTIONS.map(({ name, value }) => (
						<Option key={value} value={value}>
							{name}
						</Option>
					))}
				</Select>
				<DateRange
					className={s.item}
					value={dateRange}
					onChange={handleDateChange}
					maxDay={180}
				/>
				<Button className={s.item} onClick={handleReset}>
					重置
				</Button>
			</div>
		</div>
	);
}

Toolbox.propTypes = {
	className: PropTypes.string,
	reSearch: PropTypes.func,
	getDropdownRef: PropTypes.func,
	location: PropTypes.shape({
		search: PropTypes.string,
	}),
};

Toolbox.defaultProps = {
	className: s.toolbox,
};

export default withRouter(Toolbox);
